<template>
  <el-dialog
    v-el-drag-dialog
    width="1000px"
    :title="formName"
    :visible="show"
    @update:visible="updateShow"
    destroy-on-close
    v-if="show"
  >
    <el-row style="margin-top: 15px">
      <el-col :span="8" class="menuList">
        <el-input
          placeholder="输入关键字进行过滤"
          v-model="filterText"
        ></el-input>
        <el-card class="menuTree">
          <el-tree
            class="filter-tree"
            v-loading="treeDataLoading"
            :data="treeData"
            node-key="Id"
            highlight-current
            :props="defaultProps"
            :filter-node-method="filterNode"
            ref="menuTree"
            @node-click="getNodeData"
            :default-expanded-keys="menuNodeKey"
            :current-node-key="menuNodeKeyStr"
            default-expand-all
          >
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="box-card">
          <span style="font-size: 18px">菜单</span>
          <el-form
            ref="dataForm"
            :rules="rules"
            :model="form"
            label-position="right"
            label-width="140px"
          >
            <el-form-item label="菜单名称" prop="MenuName">
              <el-input
                v-model="form.MenuName"
                placeholder="请输入菜单名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="父级节点(左侧筛选)">
              <el-input
                v-model="form.MenuParentName"
                disabled
                placeholder="请选择父级节点(空为一级目录)"
              ></el-input>
            </el-form-item>
            <el-form-item label="菜单链接" prop="MenuPath">
              <el-input
                v-model="form.MenuPath"
                placeholder="请输入菜单链接"
              ></el-input>
            </el-form-item>
            <el-form-item label="菜单类型" prop="MenuType">
              <el-radio-group v-model="form.MenuType" style="width: 500px">
                <el-radio :label="true">目录</el-radio>
                <el-radio :label="false">菜单</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="菜单图标" prop="MenuIcon">
              <div class="flex">
                <el-input
                  v-model="form.MenuIcon"
                  style="width: 400px"
                  disabled
                />
                <el-popover
                  placement="bottom"
                  style="width: 100px"
                  trigger="click"
                >
                  <div class="icon-list">
                    <div
                      class="icon-item"
                      v-for="(item, iconIndex) in iconsList"
                      :key="iconIndex"
                      @click="choseIcon(item)"
                    >
                      <template v-if="calcicon(item)">
                        <i :class="item" />
                      </template>
                      <template v-else>
                        <svg-icon :icon-class="item" />
                      </template>
                      <!--  -->
                    </div>
                  </div>
                  <el-button slot="reference">选择</el-button>
                </el-popover>
              </div>
            </el-form-item>
            <el-form-item label="菜单排序" prop="MenuSort">
              <el-input
                type="number"
                v-model="form.MenuSort"
                placeholder="请输入菜单排序"
              ></el-input>
            </el-form-item>
            <el-form-item label="菜单备注" prop="Remark">
              <el-input
                v-model="form.Remark"
                placeholder="请输入菜单备注"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-card>
        <el-card class="box-card" v-if="form.Id">
          <div style="font-size: 18px">按钮</div>
          <systemButton :menu-id="form.Id"></systemButton>
        </el-card>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button @click="updateShow(false)"> 取消 </el-button>
      <el-button type="primary" @click="save"> 保存 </el-button>
    </div>
  </el-dialog>
</template>
<script>
import { deepClone } from '@/utils'
import { getList, save, GetById } from '@/api/system/menu'
import { mapState } from 'vuex'
import elementIcons from '@/views/icons/element-icons'
import svgIcons from '@/views/icons/svg-icons'
import systemButton from '@/views/System/systemButton'

export default {
  components: { systemButton },
  props: {
    show: {
      type: Boolean,
      default () {
        return false
      }
    },
    isAddChild: {
      type: Boolean,
      default () {
        return false
      }
    },
    formData: {
      type: Object,
      default () {
        return {}
      }
    },
    PlatFormType: {
      type: String,
      default: 'PC'
    },
    formName: {
      type: String,
      default: '编辑'
    }
  },
  data () {
    return {
      form: {},
      formTmpl: {
        MenuIcon: '',
        MenuParentName: '',
        MenuParentId: '00000000-0000-0000-0000-000000000000',
        PlatFormType: 'PC',
        MenuType: true
      },
      rules: {
        MenuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
        MenuPath: [{ required: true, message: '请输入菜单链接', trigger: 'blur' }],
        // Remark: [{ required: true, message: '请输入菜单标识', trigger: 'blur' }],
      },
      listQuery: {
        MenuName: "", //页面名称
        IsPaging: false, //是否分页
        SortName: "MenuSort", //排序栏位
        SortType: true //排序类型｛True：正序；Flase：反序｝
      },
      filterText: '',
      defaultProps: {
        children: 'ChildList',
        label: 'MenuName'
      },
      currentMenuId: '',
      treeData: [
        {
          Id: undefined,
          MenuName: '一级目录'
        }
      ],
      treeDataLoading: true,
      menuNodeKey: [],
      menuNodeKeyStr: '',
      elementIcons: elementIcons,
      svgIcons: svgIcons
    }
  },
  computed: {


    iconsList () {
      let eleicon = this.$deepClone(this.elementIcons)
      eleicon = eleicon.map(item => {
        return 'el-icon-' + item
      })
      let l = this.svgIcons.concat(eleicon)
      return l
    },
    ...mapState({
      userId: state => state.user.id,
    }),
  },
  watch: {
    formData: {
      deep: true,
      immediate: true,
      handler (val) {
        // console.log('触发一次', val)
        if (this.$refs['dataForm']) {
          this.$refs['dataForm'].clearValidate()
        }
        this.filterText = ''
        if (this.isAddChild) {
          // console.log('增加子菜单')
          this.form = { ...val, MenuName: '' }
        } else {
          // console.log('这是编辑')
          if (val.Id) {
            GetById({ Id: val.Id }).then(res => {
              this.form = deepClone({ ...res.Data })
            })
          } else {
            this.form = deepClone(this.formTmpl)
          }

        }

      }
    },
    filterText: {
      handler (val) {
        this.$refs.menuTree.filter(val)
      }
    }
  },
  methods: {
    choseIcon (item) {
      this.$set(this.form, 'MenuIcon', item)
      // form.MenuIcon = item
    },
    calcicon (icon) {
      if (icon.includes('el-icon')) {

        return true
      }
      return false
    },
    updateShow (val) {
      this.$emit('update:show', val)
    },
    afterSave () {
      this.$notify({
        title: '操作成功',
        message: 'success',
        type: 'success',
        duration: 2000
      })
      this.updateShow(false)
      this.$emit('finish')
    },
    save () {
      this.$refs['dataForm'].validate((valid) => {
        const formData = deepClone(this.form)
        if (this.isAddChild) {
          //如果是新增子菜单页面
          formData.Id = '00000000-0000-0000-0000-000000000000'
          formData.MenuIcon = ''
        }
        formData.PlatFormType = this.PlatFormType
        if (valid) {
          if (this.form.Id) {
            save(formData).then(() => {
              this.afterSave()
            })
          } else {
            save(formData).then(() => {
              this.afterSave()
            })
          }
        }
      })
    },
    getMenuList () {
      let that = this;
      that.treeDataLoading = true
      that.treeData = [
        {
          Id: '00000000-0000-0000-0000-000000000000',
          MenuName: '一级目录'
        }
      ]
      let listQuery = Object.assign(that.listQuery, { PlatFormType: this.PlatFormType })
      getList(listQuery).then((res) => {
        that.treeData = that.treeData.concat(res.Data)
        that.treeDataLoading = false
        console.log(that.treeData)
      }).catch(err => {
        if (err.Code == 202) {
          that.treeData = []
        }
      })
    },
    filterNode (value, data) {
      if (value === '') return true;
      return data.MenuName.indexOf(value) !== -1;
    },
    getNodeData (data) {
      console.log(data)
      this.form.MenuParentId = data.Id
      this.form.MenuParentName = data.MenuName
      this.$forceUpdate()
    },
    generateElementIconCode (symbol) {
      return `<i class="el-icon-${symbol}" />`
    },
  },
  created () {
    this.getMenuList()
  }
}
</script>
<style lang="scss" scoped>
.icon-list {
  width: 300px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  max-height: 300px;
  overflow-y: scroll;
  .icon-item {
    font-size: 30px;
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    &:hover {
      color: blue;
      cursor: pointer;
      background: #dddddd;
      border-radius: 6px;
    }
  }
}
</style>
